package com.pd.kit;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by dong peng
 * DATE : 2016/12/18
 * TIME : 22:57.
 *
 * 借助dom4j处理xml文件数据与String类型转换
 */
public final class XmlKit {

    private static final String ROOT_NAME = "xml";
    private static final String CHAR_SET = "UTF-8";

    private XmlKit(){}

    public static String escape(String value) {
        return "![CDATA[" + value + "]]";
    }

    /**
     * 将xml格式数据的字符串解析为Map类型
     * 当然xml结构也只支持一层
     * @param text
     * @return
     * @throws DocumentException
     */
    public static Map<String,String> xmlToMap(String text) throws DocumentException {
        Document document = DocumentHelper.parseText(text);
        Map map = documentToMap(document);
        return map;
    }


    /**
     * Map转xml
     * @param map
     * @return
     */
    public static String mapToXml(Map<String,String> map) {
        Document document = DocumentHelper.createDocument();
        Element root = DocumentHelper.createElement(ROOT_NAME);
        document.add(root);
        for(Map.Entry<String,String> entry : map.entrySet()) {
            root.addElement(entry.getKey()).addText(entry.getValue());
        }

        return document.asXML();
    }

    /**
     * Map转xml  美化版
     * @param map
     * @return
     */
    public static String mapToXmlPretty(Map<String,String> map) {
        Document document = DocumentHelper.createDocument();
        Element root = DocumentHelper.createElement(ROOT_NAME);
        document.add(root);
        for(Map.Entry<String,String> entry : map.entrySet()) {
            root.addElement(entry.getKey()).addText(entry.getValue());
        }

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(CHAR_SET);
        format.setIndent(false);

        StringWriter writerBuf = new StringWriter();
        XMLWriter writer = new XMLWriter(writerBuf, format);
        try {
            writer.write(document);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String result = writerBuf.toString();

        try {
            writerBuf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result; //.replaceAll("\n|\r", "");
    }

    /**
     * 从文件中加载解析xml：xml标签的名字作为Map的key，xml标签的内容作为Map的value
     * 只针对一层xml节点
     *
     * @param fileName
     * @return
     * @throws DocumentException
     */
    public static Map<String,String> parseXml(String fileName) throws DocumentException {

        if(fileName == null || "".equals(fileName)) {
            throw new RuntimeException("xml文件解析失败：确认文件是否在classes目录下.............");
        }

        // 依赖dom4j的jar包解析xml数据
        String filePath = XmlKit.class.getResource("/").getPath()+fileName;
        File file = new File(filePath);
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(file);
        Map map = documentToMap(document);

        return  map;
    }

    private static Map<String,String> documentToMap(Document document) {
        Map<String,String> resultMap = new HashMap();
        Element root = document.getRootElement();
        for(Iterator i = root.elementIterator(); i.hasNext(); ){
            Object obj = i.next();
            if(obj instanceof Element) {
                Element e = (Element) obj;
                resultMap.put(e.getName(),e.getText());
            }
        }

        return  resultMap;
    }


}
